<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, computed, watch, getCurrentInstance, defineExpose, defineProps, defineEmits, onMounted, reactive } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { cloneDeep } from "@pureadmin/utils";
import Dept from "~icons/ri/git-branch-line";
import ResetIcon from "~icons/ri/restart-line";
import More2Fill from "~icons/ri/more-2-fill";
import OfficeBuilding from "~icons/ep/office-building";
import LocationCompany from "~icons/ep/add-location";
import ExpandIcon from "~icons/ri/arrow-drop-down-fill";
import UnExpandIcon from "~icons/ri/arrow-drop-up-fill";
import SearchIcon from "~icons/ri/search-line";

interface Tree {
	id: number;
	name: string;
	highlight?: boolean;
	children?: Tree[];
}

const emit = defineEmits(["tree-select"]);
const treeLoading = ref(false);
// 组织列表
const treeData = computed(() => {
	treeLoading.value = true;
	const rawOptions = useUserStoreHook().deptOptions;
	let deptOptions = cloneDeep(rawOptions) || [];
	if (!deptOptions || deptOptions.length === 0) {
		useUserStoreHook().getOrgListAndRoles(); // 执行获取数据的函数
	}
	const newDeptOptions = cloneDeep(rawOptions) || [];
	// 初始化下当前登录人的组织信息
	if (useUserStoreHook().roles.some(item => item == "admin")) {
		// 在顶部插入全部
		if (deptOptions.length > 0 && deptOptions[0]?.name !== "全部") {
			deptOptions.unshift({
				id: "",
				name: "全部",
				highlight: true
			});
		}
	} else {
		const userOrgId = useUserStoreHook().userInfo?.orgId;
		if (userOrgId) {
			const findDept = newDeptOptions.find(item => item.id === userOrgId);
			deptOptions = [];
			// deptOptions = {
			// 	...findDept,
			// 	id: useUserStoreHook().userInfo?.orgId,
			// 	parentId: useUserStoreHook().userInfo?.parentId,
			// 	name: useUserStoreHook().userInfo?.orgName,
			// 	children: newDeptOptions,
			// 	hasChildren: true,
			// 	highlight: true
			// };
			deptOptions.unshift({
				id: useUserStoreHook().userInfo?.orgId,
				parentId: useUserStoreHook().userInfo?.parentId,
				name: useUserStoreHook().userInfo?.orgName,
				children: newDeptOptions,
				hasChildren: true,
				highlight: true
			});
		}
	}
	console.log(deptOptions);
	treeLoading.value = false;
	return deptOptions;
});
const treeRef = ref();
const isExpand = ref(true);
const searchValue = ref("");
const highlightMap = ref({});
const { proxy } = getCurrentInstance();
const defaultProps = {
	children: 'children',  // 需确保数据中存在children字段
	label: 'name',         // 显示名称字段映射
	isLeaf: data => !data.hasChildren  // 叶子节点判断逻辑
};
const buttonClass = computed(() => {
	return [
		"h-[20px]!",
		"text-sm!",
		"reset-margin",
		"text-(--el-text-color-regular)!",
		"dark:text-white!",
		"dark:hover:text-primary!"
	];
});

const filterNode = (value: string, data: Tree) => {
	if (!value) return true;
	return data.name.includes(value);
};
const form = reactive({
	orgId: ""
});

function nodeClick(value) {
	const nodeId = value.$treeNodeId;
	highlightMap.value[nodeId] = highlightMap.value[nodeId]?.highlight
		? Object.assign({ id: nodeId }, highlightMap.value[nodeId], {
			highlight: false
		})
		: Object.assign({ id: nodeId }, highlightMap.value[nodeId], {
			highlight: true
		});
	Object.values(highlightMap.value).forEach((v: Tree) => {
		if (v.id !== nodeId) {
			v.highlight = false;
		}
	});
	emit(
		"tree-select",
		highlightMap.value[nodeId]?.highlight
			? Object.assign({ ...value, selected: true })
			: Object.assign({ ...value, selected: false })
	);
}

function toggleRowExpansionAll(status) {
	isExpand.value = status;
	const nodes = (proxy.$refs["treeRef"] as any).store._getAllNodes();
	for (let i = 0; i < nodes.length; i++) {
		nodes[i].expanded = status;
	}
}

/** 重置组织树状态（选中状态、搜索框值、树初始化） */
function onTreeReset() {
	highlightMap.value = {};
	searchValue.value = "";
	toggleRowExpansionAll(true);
}

watch(
	() => searchValue, (val) => {
		console.log(val);
		treeLoading.value = true;
		treeRef.value!.filter(val);
		treeLoading.value = false;
	});
onMounted(() => {
	// 初始化下当前登录人的组织信息
	if (useUserStoreHook().roles.some(item => item == "admin")) {
		form.orgId = "";
	} else {
		form.orgId = useUserStoreHook().orgId;
	}
})
defineExpose({ onTreeReset });
</script>

<template>
	<div v-loading="treeLoading" class="h-full bg-bg_color overflow-hidden relative"
		:style="{ minHeight: `calc(100vh - 141px)` }">
		<div class="flex items-center h-[34px]">
			<el-input v-model="searchValue" class="ml-2" size="small" placeholder="请输入组织名称" clearable>
				<template #suffix>
					<el-icon class="el-input__icon">
						<IconifyIconOffline v-show="searchValue.length === 0" :icon="SearchIcon" />
					</el-icon>
				</template>
			</el-input>
			<div class="ml-[5px] pt-[10px] mr-[5px]">
				<el-dropdown :hide-on-click="false">
					<IconifyIconOffline :icon="More2Fill" />
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item>
								<el-button :class="buttonClass" link type="primary"
									:icon="useRenderIcon(isExpand ? ExpandIcon : UnExpandIcon)"
									@click="toggleRowExpansionAll(isExpand ? false : true)">
									{{ isExpand ? "折叠全部" : "展开全部" }}
								</el-button>
							</el-dropdown-item>
							<!-- <el-dropdown-item>
              <el-button
                :class="buttonClass"
                link
                type="primary"
                :icon="useRenderIcon(Reset)"
                @click="onTreeReset"
              >
                重置状态
              </el-button>
            </el-dropdown-item> -->
						</el-dropdown-menu>
					</template>
				</el-dropdown>
			</div>
		</div>
		<el-divider />
		<el-scrollbar height="calc(90vh - 78px)">
			<div v-if="treeData && treeData.length > 0" class="pt-[8px]">
				<el-tree ref="treeRef" :data="treeData" node-key="id" size="small" :props="defaultProps" default-expand-all
					:expand-on-click-node="false" :filter-node-method="filterNode" @node-click="nodeClick">
					<template #default="{ node, data }">
						<div :class="[
							'rounded-sm',
							'flex',
							'items-center',
							'select-none',
							'hover:text-primary',
							searchValue.trim().length > 0 &&
							node.label.includes(searchValue) &&
							'text-red-500',
							highlightMap[node.id]?.highlight ? 'dark:text-primary' : ''
						]" :style="{
							color: highlightMap[node.id]?.highlight
								? 'var(--el-color-primary)'
								: '',
							background: highlightMap[node.id]?.highlight
								? 'var(--el-color-primary-light-7)'
								: 'transparent'
						}">
							<!-- <IconifyIconOffline :icon="data.type === 1
								? OfficeBuilding
								: data.type === 2
									? LocationCompany
									: Dept
								" /> -->
							<span class="w-[120px]! truncate!" :title="node.label">
								{{ node.label }}
							</span>
						</div>
					</template>
				</el-tree>
			</div>
		</el-scrollbar>
	</div>
</template>

<style lang="scss" scoped>
:deep(.el-divider) {
	margin: 0;
}

:deep(.el-tree) {
	--el-tree-node-hover-bg-color: transparent;
}
</style>
